package top.gaui.nurse.controller;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import top.gaui.nurse.entity.Attendance;
import top.gaui.nurse.repository.AttendanceRepository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Fujie_Zeng
 * @version 1.0
 * @date 2020/4/20 11:14
 */
@RestController
@RequestMapping("/attendance")
public class AttendanceHandler {
    @Autowired
    private AttendanceRepository attendanceRepository;

    @GetMapping({"/find/{num}/{department}/{date1}/{date2}/{page}/{size}",
            "/find/{department}/{date1}/{date2}/{page}/{size}",
            "/find/{num}/{department}/{page}/{size}",
            "/find/{department}/{page}/{size}"})
public Page<Attendance> find(@PathVariable(required = false)Integer num, @PathVariable String department,@PathVariable(required = false)String date1,@PathVariable(required = false)String date2, @PathVariable Integer page, @PathVariable Integer size) {
        Specification<Attendance> specification = new Specification<Attendance>() {
            @SneakyThrows
            @Override
            public Predicate toPredicate(Root<Attendance> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (num !=null) {
                    predicateList.add(criteriaBuilder.equal(root.get("num").as(Integer.class), num));
                }
                if(department != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("department").as(String.class),department));
                }
                if(date1 != null&&date2 !=null) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date11= format.parse(date1);
                    Date date22= format.parse(date2);
                    predicateList.add(criteriaBuilder.between(root.get("on"),date11,date22));
                }

                Predicate[] pre = new Predicate[predicateList.size()];
                criteriaQuery.orderBy(criteriaBuilder.asc(root.get("id")));
                return criteriaQuery.where(predicateList.toArray(pre)).getRestriction();
            }
        };
        PageRequest request = PageRequest.of(page-1,size);
        return attendanceRepository.findAll(specification, request);


    }
}
